export function mongoIdToDate(_id: string): Date {
  return new Date(parseInt(`${_id.substr(0, 8)}`, 16) * 1000);
}

/**
 * 获取文件拓展名 123.png -> .png | ""
 * @param {string} path
 * @return {string} ext
 */
export const getExt = (path: string): string => {
  const split = path.match(/\w+(\.\w+)$/);
  return split ? split[1] : "";
};

/**
 * 常见的图片后缀名数组
 */
export const imageExt = [".gif", ".png", ".jpg", ".jpeg", ".avif", ".webp"];

/**
 * blob文件下载
 * @param {Blob} blob
 * @param {string} fileName
 * @return {*} void
 */
export const downloadBlob = (blob: Blob, fileName: string) => {
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  a.click();
  URL.revokeObjectURL(url);
};

export function copyToClipboard(text: string) {
  if (navigator.clipboard) {
    return navigator.clipboard.writeText(text);
  }
  // @ts-ignore
  else if (window.clipboardData && window.clipboardData.setData) {
    // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
    // @ts-ignore
    return window.clipboardData.setData("Text", text);
  } else {
    var textarea = document.createElement("textarea");
    textarea.textContent = text;
    textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in Microsoft Edge.
    document.body.appendChild(textarea);
    textarea.select();
    try {
      return document.execCommand("copy"); // Security exception may be thrown by some browsers.
    } catch (ex) {
      console.warn("Copy to clipboard failed.", ex);
      return false;
    } finally {
      document.body.removeChild(textarea);
    }
  }
}

/**
 * @description: 随机rgba格式颜色
 * @return {string} rgba
 */
const { floor, random } = Math;
export function randomRGBA(): string {
  const r = floor(random() * 250);
  const g = floor(random() * 250);
  const b = floor(random() * 250);
  const a = random();
  return `rgba(${r},${g},${b},${a})`;
}

/**
 * @description: 随机十六进制
 * @return {string} #xxxxxx
 */
export function randomColor(): string {
  // .padEnd 有时候会出现不满6位的十六进制颜色canvas会报错，使用padEnd填充
  return (
    "#" +
    Math.round(Math.random() * 0xffffff)
      .toString(16)
      .padEnd(6, "9")
  );
}

/**
 * @description: 随机十六进制透明色
 * @return {string} #xxxxxxxx
 */
export function randomTransparentColor(): string {
  // .padEnd(8, "9") 有时候会出现不满8位的十六进制颜色canvas会报错，使用padEnd填充满8位
  return (
    "#" +
    Math.round(Math.random() * 0xffffffff)
      .toString(16)
      .padEnd(8, "9")
  );
}
